from django.shortcuts import render, HttpResponse
from apps.crm.models import CourseRecord, ScoreRecord
from apps.student.forms import HomeWorkForm
from django.contrib.auth.decorators import login_required

# Create your views here.
@login_required
def course(request):
    # return HttpResponse('This is student course')
    #a = CourseRecord.objects.all()
    # a = request.user.related_student.my_class.related_course_record.all()
    try:
        st = request.user.related_student
        contents = st.my_class.related_course_record.all()
    except Exception as ex:
        contents = ""
    # contents = request.user.related_student.my_class.related_course_record.all()
    kwgs = {
        "course_records": contents
    }
    print(kwgs, "xxx")
    return render(request, 'student/course.html', kwgs)

@login_required
def homework(request, course_record_id):
    if request.method == 'POST':
        print(request.FILES)
        form = HomeWorkForm(request.POST, request.FILES)
        if form.is_valid():
            print('data ok')
            student = request.user.related_student
            course_record = CourseRecord.objects.get(pk=course_record_id)
            score_record = ScoreRecord.objects.filter(student=student, course_record=course_record)
            homework_replay_content = form.cleaned_data['homework_replay_content']
            homework_replay_attach = form.cleaned_data['homework_replay_attach']
            if score_record:
                score_record = score_record.first()
                print('*'*10)
                print(score_record)
                score_record.homework_replay_content = homework_replay_content
                score_record.homework_replay_attach = homework_replay_attach
                score_record.save()
            else:
                score_record = ScoreRecord(student=student, course_record=course_record,
                                         homework_replay_content=homework_replay_content,
                                         homework_replay_attach=homework_replay_attach)
                score_record.save()
                print(student, course_record)
        else:
            print('data error')
        kwgs = {'form': form}
    else:
        form = HomeWorkForm()
        kwgs = {'form': form}

    return render(request, 'student/homework.html', kwgs)

